import { ECharts } from "echarts";

let template = `
<div class='statistic-container'>
    <div class='statistic-header'>
        <span class='header-target'>Target</span>
        <span class='header-value'>Min</span>
        <span class='header-value'>Max</span>
        <span class='header-value'>Avg</span>
        <span class='header-value' title='Current'>Cur</span>
    </div>
    <div class='statistic-body'>
        <ul class='statistic-list'>
            <li>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                <span></span>
            <li>
        </ul>
    </div>
</div>`;

const unSelectName = 'unselect';
let onlySelectedTarget = '';
export class StatisticUnit {
    private $statisticList: JQuery<HTMLElement>;
    private curSelected: { [key: string]: boolean };

    constructor(private myChart: ECharts, private $info: JQuery<HTMLElement>, private div: HTMLDivElement) {
        $info.html(template);

        this.$statisticList = $info.find('.statistic-list');
        this.fixContentWidth();

        this.curSelected = (this.myChart.getOption().legend as any)[0].selected;
        this.bindHoverEvent();
    }

    public fixContentWidth() {
        this.$statisticList.width(this.$info.find('.statistic-container').width()! - 17);
    }

    private bindHoverEvent() {
        this.$statisticList.on('mouseenter', '.statistic-target', (e) => {
            let targetName = $(e.target).text();
            this.myChart.dispatchAction({
                type: 'highlight',
                seriesName: targetName
            });

        });

        this.$statisticList.on('mouseout', '.statistic-target', (e) => {
            let targetName = $(e.target).text();
            this.myChart.dispatchAction({
                type: 'downplay',
                seriesName: targetName
            });
        });

        this.$statisticList.on('click', '.statistic-target', (e) => {
            let curEchartOption = this.myChart.getOption();
            let allTargetNames = curEchartOption.series?.map(a => a.name);

            if (this.$statisticList.find('li.' + unSelectName).length > 0 && !$(e.target).closest('li').hasClass(unSelectName)) {
                this.curSelected = {};
                for (let cur of allTargetNames!) {
                    this.curSelected[cur!] = true;
                }
                onlySelectedTarget = '';
            } else {
                this.curSelected = {};
                for (let cur of allTargetNames!) {
                    this.curSelected[cur!] = false;
                }

                let targetName = $(e.target).text();
                this.curSelected[targetName] = this.curSelected[targetName] === undefined ? false : !this.curSelected[targetName];

                onlySelectedTarget = targetName;
            }

            this.myChart.setOption({
                legend: {
                    selected: this.curSelected
                }
            });

            this.calcStatistic();
        });
    }

    public calcStatistic(): void {
        let curSeries = this.myChart.getOption().series!;

        let $insertList = curSeries.map(item => {
            let vals = item.data!.map((a: any) => a[1]) as number[];
            let curLiClassName = this.curSelected[item.name!] === false ? unSelectName : "";
            if (item.name === onlySelectedTarget) {
                curLiClassName += ' onlySelected';
            }
            if (vals.length <= 0) {
                return $();
            }
            let min = Math.min.apply(this, vals).toFixed(2);
            let max = Math.max.apply(this, vals).toFixed(2);
            let avg = (vals.reduce((sum, curVal) => {
                return sum + curVal
            }) / vals.length).toFixed(2);
            let cur = vals[vals.length - 1].toFixed(4);

            let $curLi = $(`
<li class='${curLiClassName}'>
    <span class='statistic-target' title='${this.safeHtml(item.name!)}'>${this.safeHtml(item.name!)}</span>
    <span class='statistic-value' title='${min}'>${min}</span>
    <span class='statistic-value' title='${max}'>${max}</span>
    <span class='statistic-value' title='${avg}'>${avg}</span>
    <span class='statistic-value' title='${cur}'>${cur}</span>
</li>`);
            return $curLi;
        });

        this.$statisticList.empty();
        this.$statisticList.append($insertList);

        // var html = this.$statisticList.html();
        // this.$statisticList.append(html);
        // this.$statisticList.append(html); this.$statisticList.append(html); this.$statisticList.append(html); this.$statisticList.append(html); this.$statisticList.append(html); this.$statisticList.append(html);
    }

    private safeHtml(str: string): string {
        return $('<div/>').text(str).html();
    }
}